let Koa = require('koa');

let Router = require('koa-router');

var bodyParser = require('koa-bodyparser');

let app = new Koa();

let router = new Router();

let query = require('./db/index');

app.use(bodyParser());

app.use(router.routes())
    .use(router.allowedMethods());

//  /api/list    /api/add

// app.use(async (ctx,next) => {
    
// })

/**
 * [
 * 
 *      {
 *          id:1,       //唯一id
 *          username:'zs',
 *          age:18,
 *          city:'北京,
 *          phone:12121212
 *      }
 * ]
 * 
 * 
*/

router.get('/api/list',async (ctx) => {
    //pagenum 第几页  limit 每页的条数
    //一共有多少条数据  total
    let {pagenum=1,limit=5,key=''} = ctx.request.query;
    // 0   5    
    // 5   5
    // 10  5

    let startIndex = (pagenum-1)*limit;
    
    //1.是先做分页后做条件筛选？ 2.先筛选再分页？

    let sql = 'select * from userlist';
    sql += key ? ' where city=? ' : ' ';
    sql += `limit ${startIndex},${limit}`;

    console.log(sql)
    let result = await query(sql,[key]);

    let countSql = 'select count(*) from userlist';

    countSql += key ? ' where city=?' : '';

    console.log(countSql)

    let total = await query(countSql,[key]);


    ctx.body = {
        code:1,
        data:result,
        total:total[0]['count(*)']
    }
})


//添加

router.post('/api/add',async (ctx) => {
    console.log(ctx.request.body);
    let {username,age,phone,city} = ctx.request.body;
    let time = new Date();
    //容错处理
    if(username && age && /\d{11}/.test(phone) && city){
        //添加
        //错误处理机制  try{}catch(e){}
        try{
            //尝试添加
            await query('insert into userlist (username,age,phone,city,time) values (?,?,?,?,?)',[username,age,phone,city,time])
            ctx.body = {
                code:1,
                msg:'添加成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        //参数有误
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }
})

//删除
router.delete('/api/del',async (ctx) => {
    let {id} = ctx.request.query;
    if(id){
        try{
            await query('delete from userlist where id=?',[id]);
            ctx.body = {
                code:1,
                msg:'删除成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        //参数有误
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }
})

//更新


router.post('/api/add',(ctx) => {
    ctx.body = "添加成功"
})

app.listen(3000,() => {
    console.log("服务启动成功")
})

//let const var 的区别：